// pages/cart/index.js
// 引入request异步请求
import request from '../../utils/request.js'
Page({
  data: {
    // 收货地址
    address: {},
    // 购物车商品数据
    goods: [],
    // 保存总价格
    allPrice: 0,
    // 购物车总数量
    allNumber: 0,
    // 记录全选的状态
    allSelect: true
  },
  onLoad() {
    // 拿到本地储存数据（收货地址）
    this.setData({
      address: wx.getStorageSync('address') || {}
    })
  },
  onShow() {
    // 拿购物车商品数据
    let cartList = wx.getStorageSync('goods') || [];
    let goods = cartList.filter(v => {
      return v.cart_select === true;
    })
    this.setData({
      goods
    })

    // 加载计算总价格
    this.handleGetAllprice();
  },
  // 点击获取收货地址的函数
  handleGetAddress() {
    wx.chooseAddress({
      success: res => {
        // 将获取的收货地址保存起来
        this.setData({
          address: {
            name: res.userName,
            phone: res.telNumber,
            getAddress: res.provinceName + res.cityName + res.countyName + res.detailInfo
          }
        })
        // 将收货地址储存到本地
        wx.setStorageSync('address', this.data.address)
      }
    })
  },
  // 计算总价格的处理
  handleGetAllprice() {
    var price = 0;
    var num = 0;
    this.data.goods.forEach(v => {
      // 判断如果是选中状态就计算
      if (v.cart_select === true) {
        // 计算总价格
        price += v.cart_number * v.cart_price;
        //  计算总数量
        num += v.cart_number
      }
    })

    this.setData({
      allPrice: Number(price).toFixed(2),
      allNumber: num
    })
  },
  // 获取用户信息
  getUserInfo() {
    let token = wx.getStorageSync('token')
    if (!token) {
      // 跳转的授权页面
      wx.navigateTo({
        url: "../authorize/index"
      })
    } else {
      // 开始创建订单
      const orderGoods = this.data.goods.map(v => {
        return {
          goods_id: v.cart_price,
          goods_number: v.cart_number,
          goods_price: v.cart_price
        }
      })
      //  创建订单
      request({
        url: '/my/orders/create',
        method: 'post',
        header: {
          Authorization: token
        },
        data: {
          order_price: this.data.allPrice,
          consignee_addr: this.data.address.getAddress,
          goods: orderGoods
        }
      }).then(res => {
        // console.log(res)
        wx.showToast({
          title: res.data.meta.msg,
          icon: 'success',
          duration: 2000
        })
        //  拿到支付参数
        const { order_number } = res.data.message
        //  发起支付请求
        request({
          url: '/my/orders/req_unifiedorder',
          method: 'post',
          header: {
            Authorization: token
          },
          data: {
            order_number
          }
        }).then(res => {
          let { pay } = res.data.message;
          // 调用微信支付接口
          wx.requestPayment(pay)
        })
        // 将没付款的商品保存到本地购物车
        let cartData = wx.getStorageSync('goods') || [];
        const goodsList = cartData.filter(v=>{
          return !v.cart_select;
        })
        wx.setStorageSync('goods', goodsList)
      })
    }
  }

})